#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <fcntl.h>

#define BUF_SIZE 1024
#define NAME_SIZE 256
void error_handling(char *message);
void compute_md5(char *file_name, char *result);

int main(int argc, char *argv[])
{
    int serv_sock;
    char buf[BUF_SIZE];
    struct sockaddr_in serv_adr, clnt_adr;
    socklen_t clnt_adr_sz;
    FILE * fp;
    char file_name[NAME_SIZE];
    char file_name_recv[NAME_SIZE];
    char md5_send[33];
    char md5_recv[33];

    serv_sock=socket(PF_INET, SOCK_STREAM, 0);   
    memset(&serv_adr, 0, sizeof(serv_adr));
    serv_adr.sin_family=AF_INET;
    serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);
    serv_adr.sin_port=htons(8080);

    if(bind(serv_sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr))==-1)
        error_handling("bind() error");
    if(listen(serv_sock, 5)==-1)
        error_handling("listen() error");

    clnt_adr_sz=sizeof(clnt_adr);    
    int clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_adr,&clnt_adr_sz);

    // Receive file name
    read(clnt_sock, file_name, NAME_SIZE);
    printf("file name is: %s \n",file_name);
    for(int i=0;i<NAME_SIZE;i++)
    {
        //printf("file_name[%d]=%c\n",i,file_name[i]);
        if(file_name[i] > 0 ){
        file_name_recv[i] = file_name[i];
        }
        file_name_recv[i+1] = '\0';
    }

    read(clnt_sock, md5_send, NAME_SIZE);
    printf("file md5_send is: %s \n",md5_send);
   
    //test
    //for(int i=0;i<30;i++)
    //{
    //    printf("file_name_recv[%d]=%c\n",i,file_name_recv[i]);
    //}

    fp=fopen(file_name_recv, "wb"); 
    if(fp == NULL)
        error_handling("File open error");

    int read_cnt;
    while((read_cnt=read(clnt_sock, buf, BUF_SIZE))!=0)
        fwrite((void*)buf, 1, read_cnt, fp);

    write(clnt_sock, "Thank you!!!", 20);
    //fflush(fp);
    fclose(fp);
     // Compute and print MD5 hash of received file
    //system("sync");
    //system("ls -lh");
    compute_md5(file_name_recv, md5_recv);
    printf("file md5_recv is: %s\n", md5_recv);

    if(strcmp(md5_send, md5_recv) == 0) {  
        printf("file transfer OK\n");  
    } else {  
        printf("file transfer NG\n");  
    }
    close(clnt_sock);       
    close(serv_sock);
    return 0;
}

void error_handling(char *message)
{
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}
void compute_md5(char *file_name, char *result)
{
    char cmd[100];
    sprintf(cmd, "md5sum %s", file_name);
    FILE* pipe = popen(cmd, "r");
    if (!pipe) return;
    char* res = fgets(result, 33, pipe);
    if (res == NULL) {
        printf("error\n");
    }
    pclose(pipe);
}